<template>
  <main>
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" status-icon :rules="rules" label-width="auto"
      class="demo-ruleForm">
      <div class="title">十方智育管理系统</div>
      <el-form-item prop="userName" >
        <el-input v-model="ruleForm.userName" prefix-icon="UserFilled"/>
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model="ruleForm.password" type="password" prefix-icon="Lock"/>
      </el-form-item>
      <el-form-item prop="code">
        <el-input v-model="ruleForm.code" prefix-icon="Lock" style="width: 140px;"/>
        <img @click="getCode" class="ml5" :src="imgCode" alt="" style="padding-left: 40px;">
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">登陆</el-button>
      </el-form-item>
     </el-form>
  </main>
</template>

<script setup>
import axios from 'axios';
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus'
import { onMounted } from 'vue';
const router = useRouter();
const ruleFormRef = ref()
const ruleForm = reactive({
  userName:'admin',
  password: '123456',
  code: '',
})
onMounted(() => {
  // 页面加载时，判断是否已登录
  getCode();
})

const imgCode = ref(''); // 图片验证码
const answer = ref(''); // 验证码答案
let timerId; // 声明一个变量来存储定时器的ID
// 获取后端验证码信息
const getCode = () => {
  // 清除之前的定时器
  if (timerId) {
    clearTimeout(timerId);
  }
  // 发送请求
  axios.get('/captcha')
  .then((res) => {
    const result = res.data;
    if(result.code == 1){
      imgCode.value = "data:image/gif;base64," + result.data.img;
      answer.value = result.data.answer;
      // 调用定时器方法
      timer();
    }
  })
}

// 定时器方法，定时2分钟后，销毁answer数据
const timer = () => {
  timerId = setTimeout(() => {
    answer.value = '';
  }, 120000);
}

const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if(ruleForm.code != answer.value){
        ElMessage({
          message: '验证码错误！',
          type: 'warning',
        })
        getCode();
        return;
   }
    if (valid) {
      axios.get('/systemUser/login', {
        params: {
          userName: ruleForm.userName,
          password: ruleForm.password
        }
      })
      .then(res => {
        console.log(res);
        let result = res.data;
        if (result.code == 1) {
          //全局保存token
  
		localStorage.setItem('userInfo', JSON.stringify(result.data));
          localStorage.setItem('token', result.data.token);
          ElMessage({
            message: '登录成功！',
            type: 'success',
          })
          router.replace('/home');
        } else {
          ElMessage({
            message: '登录失败！',
            type: 'warning',
          })
    }
      })
    }
  })
}

// 验证表单
const validateUser = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入用户名'))
  } else if (value !== ruleForm.user) {
    callback(new Error("Two inputs don't match!"))
  } else {
    callback()
  }
}
const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    if (ruleForm.checkPass !== '') {
      if (!ruleFormRef.value) return
      ruleFormRef.value.validateField('checkPass')
    }
    callback()
  }
}
// 校验
const rules = reactive({
  user: [{ validator: validateUser, trigger: 'blur' }],
  pass: [{ validator: validatePass, trigger: 'blur' }],
})

</script>

<style scoped>
main {
    height: 100vh;
    background-color: cadetblue;
    display: flex;
    align-items: center;
    justify-content: center;
}
.title{
    text-align: center;
    font-size: 20px;
    padding: 20px 0;
}
.demo-ruleForm{
    background-color: white;
    padding: 0 30px;
    width: 300px;
}
.el-button{
    width: 100%;
}
</style>